ajax更新wordpress静态页面的实时阅读量

2021-08-30
473次阅读
一条评论

还是老样子,静态页面没有测试,我估计应该是可行的。在我印象里,我以前做过这种事情,当时好像第一次无效,之后刷新页面才有效果,找了不少资料,最后还是没有搞定,就放弃了。

需要两个页面:

ajax更新wordpress静态页面的实时阅读量

前台的ajax请求代码:

<!--更新浏览量-->
<?php if  (is_singular()) : ?>
<script language="javascript" type="text/javascript">
   $.ajax({
    url: "https://cfhcx.com/wp-content/themes/mkBlog/action/views.php" ,
    type: "post",
	async: false,
    loading: false,
    data: {"post_ID": <?php the_ID(); ?>},
    dataType: "json", 
    success: function(data, textStatus, xhr) {
        if (data.error){ return false;}else{
			$("#saonian").html(results.response);
		}
    }
   });
  </script>
<?php endif ; ?>

后台需要新建一个php文件来处理数据:

<?php
require( dirname(__FILE__).'/../../../../wp-load.php' );
nocache_headers();
$post_ID = isset($_POST['post_ID']) ? (int) $_POST['post_ID'] : 0;
if ($post_ID!=0 ) {
	$post_views = (int) get_post_meta($post_ID, 'views', true);
		if (!update_post_meta($post_ID, 'views', ($post_views + 1))) {
			add_post_meta($post_ID, 'views', 1, true);
		}
	$post_views = (int) get_post_meta($post_ID, 'views', true);
        print_r(json_encode(array('error' => 0, 'views' => 1, 'response' => $post_views)));
        exit;
}else{
	print_r(json_encode(array('error' => 1, 'views' => 0, 'response' => $post_views)));
        exit;
}

在我网站测试是失败的,刷新网页浏览数加两个,所以不管了,以后有需要静态化网站的时候再说吧。

正文结束
自由书生
版权声明:本站原创文章,由 自由书生 于2021-08-30发表,共计1074字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(一条评论)
验证码
科华UPS电源蓄电池
2021-09-01 06:51:10 回复

博主说的不错 支持

 Windows  Chrome  中国北京北京市移动